package com.atguigu.crowd.mvc.config;

import com.atguigu.crowd.constant.CrowdContant;
import com.atguigu.crowd.exception.LoginAcctAlreadyInUserException;
import com.atguigu.crowd.exception.LoginFailedException;
import com.atguigu.crowd.util.CrowdUtil;
import com.atguigu.crowd.util.ResultEntity;
import com.google.gson.Gson;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @ControllerAdvice表示当前类是基于注解的异常处理器
 */
@ControllerAdvice
public class CrowdExceptionResolver {

    //admin添加修改的异常处理方法
    @ExceptionHandler(value = LoginAcctAlreadyInUserException.class)
    public ModelAndView LoginAcctAlreadyInUserException(LoginAcctAlreadyInUserException exception, HttpServletRequest request, HttpServletResponse response) throws IOException {
        String viewName="admin-add";
        ModelAndView modelAndView = commonResolve(viewName, exception,request,response);

        return modelAndView;
    }


    //异常处理方法
    @ExceptionHandler(value = NullPointerException.class)
    public ModelAndView resolveNullPointerException(NullPointerException exception, HttpServletRequest request, HttpServletResponse response) throws IOException {
        String viewName="error";
        ModelAndView modelAndView = commonResolve(viewName, exception,request,response);

        return modelAndView;
    }

    /**
     * 登录失败异常处理方法
     * @return
     */
    @ExceptionHandler(value = LoginFailedException.class)
    public ModelAndView resolveLoginFailedException(LoginFailedException exception,HttpServletRequest request, HttpServletResponse response) throws IOException {

        String viewName="admin-login";

        ModelAndView modelAndView = commonResolve(viewName, exception, request, response);

        return modelAndView;
    }


    //公共方法
    private ModelAndView commonResolve(String viewName,Exception exception,HttpServletRequest request,HttpServletResponse response) throws IOException {
        //判断请求类型
        if(CrowdUtil.judgeRequestType(request)){
            //当前请求是Ajax请求

            //创建ResultEntity对象
            ResultEntity<Object> failed = ResultEntity.failed(exception.getMessage());

            Gson gson = new Gson();

            String json = gson.toJson(failed);

            response.getWriter().write(json);

            return null;

        }
        //不是Ajax请求
        ModelAndView modelAndView = new ModelAndView();

        modelAndView.addObject(CrowdContant.ATTR_NAME_EXCEPTION,exception);

        modelAndView.setViewName(viewName);

        return modelAndView;



    }
}
